package com.cortex.carambola.view;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebView.HitTestResult;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.cortex.animation.AnimationInOut;
import com.cortex.animation.CortexAnimatin;
import com.cortex.carambola.summary.CarambolaRequestSummary;
import com.cortex.carambola.summary.CarambolaSummary;
import com.cortex.carambola.utilities.MessagesLog;
import com.cortex.carambola.utilities.Utilities;
import com.cortex.carambola.view.QuestionSummaryView.OnActionQuestionSummaryView;
import com.cortex.carambola.view.SummaryOnlineView.ActionOnSummary;
import com.cortex.carambola.view.SummaryOnlineView.OnActionSummaryViewListener;
import com.cortex.carambolasummary.R;


public class BrowserView extends RelativeLayout implements Browser{

	private WebView webView;
	private SummaryOnlineView summaryView;
	private ImageView imgSummaryOnline;
	private QuestionSummaryView questionSummaryView;
	private OnActionBrowserListener onActionBrowserListener;
	private CortexTextView tvUrlSummary;
	protected int webViewTouchY;
	protected int webViewTouchX;
	private boolean isLoading;

	public BrowserView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public BrowserView(Context context) {
		super(context);
	}
	@Override
	protected void onFinishInflate() {
		// TODO Auto-generated method stub
		super.onFinishInflate();
		init();
	}
	private void init(){
		initWebView();
		questionSummaryView = (QuestionSummaryView)findViewById(R.id.questionSummaryView);
		summaryView = (SummaryOnlineView)findViewById(R.id.summaryView);
		imgSummaryOnline = (ImageView)findViewById(R.id.imgSummaryOnline);
		initHandlers();
	}
	private void initWebView(){
		webView = (WebView)findViewById(R.id.webView);
		webView.getSettings().setLoadsImagesAutomatically(true);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setUseWideViewPort(true);
		webView.getSettings().setLoadWithOverviewMode(true);
		webView.getSettings().setPluginState(PluginState.ON);
		webView.getSettings().setDomStorageEnabled(true);
		webView.setWebViewClient(new ClientWebView());
		webView.setFocusableInTouchMode(true);
		webView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN: 
					webViewTouchX = (int) event.getX();
					webViewTouchY = (int) event.getY();
					break;
				}
				return false;
			}
		});
		webView.setOnLongClickListener(new OnLongClickListener() {
	        @Override
	        public boolean onLongClick(View v) {
	            final WebView webview = (WebView) v;
	            final HitTestResult result = webview.getHitTestResult();
	            if(result.getType()==HitTestResult.SRC_ANCHOR_TYPE) {
	            	showUrlSummaryAnimationUiThread(result.getExtra());
	    			sendMessageToListener(ActionOnBrowser.LONG_CLICK_ON_URL,result.getExtra());
	            }
	            return false;
	        }
	    });
		// to allow html5 videos in webView 
		webView.setWebChromeClient(new WebChromeClient() {
		});
		loadUrl("cnn.com");
	}
	private class ClientWebView extends WebViewClient{
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			isLoading = true;
			sendMessageToListener(ActionOnBrowser.LOAD_PAGE_STARTED,url);
		}
		public void onPageFinished(WebView view, String url) {
			isLoading = false;
			sendMessageToListener(ActionOnBrowser.LOAD_PAGE_FINISHED,url);
		}
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			Log.d(MessagesLog.APPLICATION,"should override url loding");
			return super.shouldOverrideUrlLoading(view, url);
		}
	}
	private void showUrlSummaryAnimationUiThread(final String url){
		// create textView with url 
		tvUrlSummary = new CortexTextView(getContext());
		tvUrlSummary.setText(url);
		tvUrlSummary.setVisibility(View.VISIBLE);
		tvUrlSummary.setTextColor(getResources().getColor(R.color.black));
		// set position in screen by touched 
		addView(tvUrlSummary);
		LayoutParams params = (LayoutParams) tvUrlSummary.getLayoutParams();
		params.leftMargin = webViewTouchX;
		params.topMargin = webViewTouchY;
		tvUrlSummary.setLayoutParams(params);

		// create animation to top right corner of screen
		int pxWidthScreen= (int)getContext().getResources().getDisplayMetrics().widthPixels;
		int pxHeightScreen= (int)getContext().getResources().getDisplayMetrics().heightPixels;
		int x = (int) ((pxWidthScreen - webViewTouchX));
		int y = (int) ((webViewTouchY*-1)-((pxHeightScreen-webView.getHeight())/2));						
		CortexAnimatin cortexAnimatin = new CortexAnimatin(tvUrlSummary,x,y,1500,1.0f,1.0f,0,0);
		List<Animation> animations = CortexAnimatin.createTranslateWithScale(cortexAnimatin);
		CortexAnimatin.startAnimations(tvUrlSummary, animations.toArray(new Animation[animations.size()]));
	}

	private void initHandlers(){
		imgSummaryOnline.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sendMessageToListener(ActionOnBrowser.SHOW_SUMMARY_ONLINE,webView.getUrl());
				hideSummaryOnline();
			}
		});
		questionSummaryView.setOnActionQuestionSummaryView(new OnActionQuestionSummaryView() {

			@Override
			public void getSummary(CarambolaRequestSummary requestSummary) {
				sendMessageToListener(ActionOnBrowser.QUESTION_SUMMARY_YES,webView.getUrl());
			}

			@Override
			public void igonre() {
				sendMessageToListener(ActionOnBrowser.QUESTION_SUMMARY_IGONRE,webView.getUrl());
				showSummaryOnline();
			}
		});
		summaryView.setOnActionSummaryListener(new OnActionSummaryViewListener() {
			@Override
			public void onAction(ActionOnSummary action) {
				switch(action){
				case CLOSED:
					sendMessageToListener(ActionOnBrowser.CLOSE_SUMMARY_VIEW,webView.getUrl());
					showSummaryOnline();
					break;
				case GET_SUMMARY:
					sendMessageToListener(ActionOnBrowser.SHOW_SUMMARY_VIEW,webView.getUrl());
					break;
				default:
					break;

				}
			}
		});
	}
	private void sendMessageToListener(ActionOnBrowser action,String url){
		if(onActionBrowserListener != null){
			onActionBrowserListener.onAction(action,url);
		}
	}
	public void setOnActionBrowserListener(
			OnActionBrowserListener onActionBrowserListener) {
		this.onActionBrowserListener = onActionBrowserListener;
	}
	public boolean isCanGoBack(){
		return webView.canGoBack();
	}
	public boolean isCanGoForward(){
		return webView.canGoForward();
	}
	public void goBack(){
		webView.goBack();  
	}
	public void goForward(){
		webView.goForward();  
	}
	public boolean isLoding() {
		return isLoading;
	}
	public void reload(){
		webView.reload();
	}
	public void loadUrl(String url){
		if(!url.contains("http://")){
			url = "http://" + url;
		}
		webView.loadUrl(url);
	}
	public void saveState(Bundle outState){
		webView.saveState(outState);
	}
	public void restoreState(Bundle savedInstanceState){
		webView.restoreState(savedInstanceState);
	}
	public void showSummaryOnline(){
		AnimationInOut animation = CortexAnimatin.createAnimation(imgSummaryOnline,
				R.anim.push_up_in, null);
		imgSummaryOnline.startAnimation(animation.getIn()); 
		imgSummaryOnline.setClickable(true);
	}
	public void hideSummaryOnline(){
		AnimationInOut animation = CortexAnimatin.createAnimation(imgSummaryOnline,
				null, R.anim.push_down_out);
		imgSummaryOnline.startAnimation(animation.getOut());
		imgSummaryOnline.setClickable(false);
	}
	public void showSummaryView(CarambolaSummary summary){
		summaryView.show(summary);
	}
	public CarambolaRequestSummary getRequestSummary(){
		return summaryView.getRequestSummary();
	}
	public interface OnActionBrowserListener{
		void onAction(ActionOnBrowser action,String url);
	}
	public enum ActionOnBrowser{
		QUESTION_SUMMARY_YES,
		QUESTION_SUMMARY_IGONRE,
		SHOW_SUMMARY_ONLINE,
		LOAD_PAGE_STARTED,
		LOAD_PAGE_FINISHED,
		LONG_CLICK_ON_URL,
		SHOW_SUMMARY_VIEW,
		CLOSE_SUMMARY_VIEW
	}

}
